import User from '../../entities/User'
import { recordHistory } from './history'
import { currentUser } from '../../utils/misc'
import * as autoRender from 'katex/contrib/auto-render'

let pid: string = ''

function doAccept($this: JQuery<HTMLElement>, uid: string): void {
    $this.addClass('am-disabled')
    $this.text('提交中')
    void $.ajax({
        method: 'POST',
        data: {
            'csrf-token': $('input[name="csrf-token"]').val(),
            do: 'accept',
            selected_uid: uid
        }
    }).done(function() {
        void recordHistory(pid, parseInt(uid), 'accept').then(() => {
            fetchNextTranslation()
                .then(url => { window.location.href = url })
                .catch((reason: Error) => { alert(reason.message) })
        })
    })
}

function doReject($this: JQuery<HTMLElement>, uid: string, warn: boolean): void {
    const action = warn ? 'delete-warn' : 'delete'
    void $.ajax({
        method: 'POST',
        data: {
            'csrf-token': $('input[name="csrf-token"]').val(),
            do: action,
            selected_uid: uid
        }
    }).done(function() {
        void recordHistory(pid, parseInt(uid), action).then(() => {
            $this.parent().parent().remove()
            if ($('article').length === 0) {
                fetchNextTranslation()
                    .then(url => { window.location.href = url })
                    .catch((reason: Error) => { alert(reason.message) })
            }
        })
    })
}

function genButton(clazz: string, text: string, onClick: ($this: JQuery<HTMLElement>) => void): JQuery<HTMLElement> {
    const newButton = $('<button></button>')
    newButton.attr('class', clazz)
    newButton.css('margin', '0.3em')
    newButton.text(text)
    newButton.on('click', () => { onClick(newButton) })
    return newButton
}

function rewriteButtonBehavior(): void {
    $('article > button').remove()
    const articles = $('article')
    for (let i = 0; i < articles.length; i++) {
        const article = $(articles[i])
        const uid = article.attr('data-tuid') ?? '0'
        article.append(
            genButton('am-btn am-btn-danger', '接受并好评', ($this) => {
                void new User(parseInt(uid)).addPraise({
                    author: currentUser,
                    reason: '翻译'
                }).then(() => { doAccept($this, uid) })
            }),
            genButton('am-btn am-btn-danger', '接受', ($this) => {
                doAccept($this, uid)
            }),
            $('<br/>'),
            genButton('am-btn am-btn-primary', '拒绝并警告', ($this) => {
                void new User(parseInt(uid)).addWarn({
                    author: currentUser,
                    reason: '翻译'
                }).then(() => { doReject($this, uid, true) })
            }),
            genButton('am-btn am-btn-primary', '拒绝', ($this) => {
                doReject($this, uid, false)
            })
        )
    }
}

async function fetchNextTranslation(): Promise<string> {
    return await new Promise((resolve, reject) => {
        void $.get('https://www.luogu.com.cn/webadmin/problem/translation',
            (data: string, status) => {
                if (status !== 'success') {
                    reject(Error('web error'))
                    return
                }
                const dat = $(`<tbody>${data.split('<tbody>')[1].split('</tbody>')[0]}</tbody>`)
                if (dat[0].firstElementChild === null) reject(Error('empty'))
                else resolve($(dat[0].firstElementChild).find('a').attr('href') ?? '')
            })
    })
}

function katexRender(): void {
    const articles = document.getElementsByClassName('am-article-bd')
    for (let i = 0; i < articles.length; i++) {
        autoRender.default(articles[i] as HTMLElement, {
            delimiters: [{
                left: '$$',
                right: '$$',
                display: true
            },
            {
                left: '$',
                right: '$',
                display: false
            }
            ],
            throwOnError: false
        })
    }
}

function renderProblemName(): void {
    const $problemName = $('body > div.am-cf.admin-main > div.admin-content > div > div.am-cf.am-padding > div > small')
    pid = $problemName.text()
    $problemName[0].innerHTML = "<a target='_blank' href='/problem/" + $problemName.text() + "'>" + $problemName.text() + '</a>'
}

async function renderWarnCount(): Promise<void> {
    const articles = $('.am-article')
    for (let i = 0; i < articles.length; i++) {
        const article = $(articles[i])
        const UID = article.attr('data-tuid') ?? '0'
        const warnCnt = (await (new User(parseInt(UID))).getWarns()).length
        const praiseCnt = (await (new User(parseInt(UID))).getPraises()).length
        article.find('.am-article-title').append(
            $('<span class="am-icon-thumbs-o-up" style="margin-left: .7em" />'),
            ` ${praiseCnt}`,
            $('<span class="am-icon-thumbs-o-down" style="margin-left: .7em" />'),
            ` ${warnCnt}`
        )
    }
}

async function load(): Promise<void> {
    if (window.location.href.startsWith('https://www.luogu.com.cn/webadmin/problem/translation/')) {
        GM_addStyle(`
.admin-content-body {
    background: #f3f3f3
}

fieldset {
    background: #ffffff;
    border: 1px solid #10a0ea;
    border-radius: 10px;
    padding: 20px;
}
.am-padding {
    background: #ffffff;
    border: 1px solid #10a0ea;
    border-radius: 10px;
    margin: 1rem
}
.katex-html {
    display: none
}
`)
        rewriteButtonBehavior()
        katexRender()
        renderProblemName()
        await renderWarnCount()
    }
}

export { load }
